package com.xbx.admin.service.upload.impl;

import com.xbx.baseweb.model.UploadFileModel;
import com.xbx.common.constant.CommmentConstant;
import com.xbx.common.utils.ConverVideoHelper;
import com.xbx.common.utils.MyUtils;
import com.xbx.admin.cache.FileUploadCache;
import com.xbx.admin.service.upload.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件操作类实现
 *
 * @author 89005691
 * @create 2018-10-23 15:54
 */
@Service
@Slf4j
public class UploadServerImpl implements UploadService {

    // nas盘位置
    @Value("${nsfServerPath}")
    private String nsfServerPath;

    // 文件服务器nginx映射
    @Value("${fileServerUrl}")
    private String fileServerUrl;

    /*// ffmpegpath服务器路径
    @Value("${ffmpegpath}")
    private String ffmpegpath;*/

    @Autowired
    private FileUploadCache fileUploadCache;

    /**
     * 上传文件
     *
     * @param multipartFile
     * @return
     */
    @Override
    public Map<String, String> uploadFile(MultipartFile multipartFile) {

        Map<String, String> map = new HashMap<>();

        String filePath = null;

        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();

        // 截取文件名
        int index = fileName.lastIndexOf(".");

        String suffix = fileName.substring(index);

        // 图片类型
        List<String> whiteType = Arrays.asList(CommmentConstant.UPLOAD_WHITE_TYPE.split(","));

        UploadFileModel uploadFileModel = new UploadFileModel();

        if (whiteType.contains(suffix.toLowerCase())) {

            // 上传文件
            filePath = uploadFile(multipartFile, suffix);
            if (StringUtils.isEmpty(filePath)) {

                map.put("msg", "上传文件失败");
                return map;
            }

            // 读取路径
            uploadFileModel.setVideoUrl(this.fileServerUrl + filePath.substring(nsfServerPath.length(), filePath.length()));
        } else {

            map.put("msg", "不允许上传" + suffix + "格式文件");
            return map;
        }

        String uuid = MyUtils.generateUUID();

        // 加入缓存
        this.fileUploadCache.addFileToCache(uuid, uploadFileModel);

        map.put("uuid", uuid);

        return map;
    }

    /**
     * 上传文件到nas盘
     */
    private String uploadFile(MultipartFile multipartFile, String suffix) {

        // 存放文件的路径为path+年月日+文件重命名名称
        StringBuilder filePath = new StringBuilder();
        filePath.append(nsfServerPath);
        filePath.append(File.separator);
        filePath.append(MyUtils.changeTimeByParam(MyUtils.generateTime(), MyUtils.FORMAT_YYYY_MM_DD));

        try {

            File file = new File(filePath.toString());

            if (!file.exists()) {
                file.mkdirs();
            }

            // 如果上传的是视频，则转码
            // List<String> allowType = Arrays.asList(ConverVideoHelper.ALLOW_TYPE.split(","));

            filePath.append(File.separator);
            filePath.append(MyUtils.generateTime().getTime());

            /*if(allowType.contains(suffix)){
                // 需要转码则保存源文件，源文件以old结尾
                filePath.append("_old");
            }*/

            filePath.append(suffix);

            multipartFile.transferTo(new File(filePath.toString()));

            /*if(allowType.contains(suffix)){

                // 新的文件路径
                StringBuilder newFile = new StringBuilder();

                newFile.append(file.getPath());
                newFile.append(File.separator);
                newFile.append(MyUtils.generateTime().getTime());
                newFile.append(ConverVideoHelper.FILE_TYPE_MP4);

                if (this.convertVideo(filePath.toString(), newFile.toString())) {

                    return newFile.toString();
                } else {

                    log.info("转码失败");
                    return null;
                }
            }*/
        } catch (Exception e) {
            log.error("上传文件出错", e);
            return null;
        }

        return filePath.toString();
    }

    /**
     * 转码视频
     */
    private boolean convertVideo(String videoPath, String newFile) {

        ConverVideoHelper converVideoHelper = new ConverVideoHelper(videoPath, "F:\\ffmpeg-20181024-6a11234-win64-static\\bin\\ffmpeg.exe", newFile);

        return converVideoHelper.beginConver();
    }
}
